import 'dart:async';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/dialog/privacy_agreement_dialog.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/sputils.dart';
import 'package:tender_flutter/widgets/page_indicator.dart';
import 'package:tender_flutter/widgets/part_refresh_widget.dart';
import 'package:tender_flutter/widgets/splash_animation_page.dart';

/// 启动页
class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  /// 引出带动画的widget
  SplashAnimationPage aniPage = new SplashAnimationPage();

  final PageController controller = PageController(initialPage: 0);

  final GlobalKey<PartRefreshWidgetState> indicatorKey = GlobalKey();

  @override
  void initState() {
    super.initState();

    Timer(Duration(seconds: 1), () => _showProtocolDialog());

    SPUtils.saveInstallFlag(false);
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);

    return new Stack(
      alignment: Alignment.center,
      children: <Widget>[
        //添加一个pageview
        new PageView(
          //设置为水平滚动 并添加素材
          scrollDirection: Axis.horizontal,
          controller: controller,
          children: <Widget>[
            Image.asset(RPath.imgPath + "guid_one.png", fit: BoxFit.cover),
            Image.asset(RPath.imgPath + "guid_two.png", fit: BoxFit.cover),
            aniPage,
          ],
          //翻页事件
          onPageChanged: startPagePaged,
        ),
        Positioned(
          bottom: 40,
          child: PartRefreshWidget(indicatorKey, () {
            return Indicator(
              controller: controller,
              itemCount: 3,
            );
          }),
        )
      ],
    );
  }

  void startPagePaged(int page) {
    indicatorKey.currentState.update();
    if (page == 2) {
      //当到达带按钮的页面时触发动画
      aniPage.btn.startAnimation();
    }
  }

  /// 协议弹窗
  _showProtocolDialog() {
    return showGeneralDialog(
        context: context,
        pageBuilder: (context, anim1, anim2) {},
        barrierDismissible: false,
        barrierLabel: "",
        transitionDuration: Duration(milliseconds: 150),
        transitionBuilder: (context, anim1, anim2, child) {
          return Transform.scale(
              scale: anim1.value,
              child: Opacity(
                opacity: anim1.value,
                child: WillPopScope(
                    onWillPop: () async {
                      return Future.value(false);
                    },
                    child: PrivacyAgreementDialog()),
              ));
        });
  }
}
